package cn.kailangtu.serialutils;

import android.app.Application;
import android.content.Context;
import android.hardware.usb.UsbDevice;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import java.util.ArrayList;
import cn.kailangtu.serialutils.api.SerialPortApi;
import cn.wch.uartlib.WCHUARTManager;
import cn.wch.uartlib.callback.IDataCallback;
import cn.wch.uartlib.callback.IUsbStateChange;
import cn.wch.uartlib.chipImpl.type.ChipType2;
import cn.wch.uartlib.exception.ChipException;
import cn.wch.uartlib.exception.NoPermissionException;
import cn.wch.uartlib.exception.UartLibException;

public class ComTrUsb {

    //private static final int USB_SERIAL_PID = 29987;
    private ReceiveDataCallback dataCallback;

    public static boolean isOpen = false;
    private static ComTrUsb mInstance;
    private static int baudRate = 38400;

    /*
     * 单例模式创建
     * */
    public static ComTrUsb getInstance() {
        if (mInstance == null) {
            mInstance = new ComTrUsb();
        }
        return mInstance;
    }

    /*
     * 构造函数
     * */
    private ComTrUsb() {
        monitorUSBState();
       //new ReadThread().start();

    }

    private Context mContext = null;


    private UsbDevice mUsbDevice;


    public void initContext(Application context) {
        mContext = context;
        WCHUARTManager.getInstance().init(context);

    }

    public void closeCom() {
        try {
            WCHUARTManager.getInstance().disconnect(mUsbDevice);
            WCHUARTManager.getInstance().close(mContext);
            isOpen = false;
        }
        catch(Exception e){}
    }

    public boolean openCOM(int baudRate) {
        showLog("进入了：openCOM");
        boolean isResult = false;
        ComTrUsb.baudRate = baudRate;
        try {

            //枚举符合要求的设备
            ArrayList<UsbDevice> usbDeviceArrayList = WCHUARTManager.getInstance().enumDevice();
            if (usbDeviceArrayList != null) {
                int num = usbDeviceArrayList.size();
                showLog("串口数：" + num);
                if (num > 0) {
                    for (int i = 0; i < num; i++) {
                        UsbDevice device = usbDeviceArrayList.get(i);
                        int devicePid = device.getProductId();
                        //showLog("串口详情：" + device.toString());
                        String deviceName = device.getDeviceName();
                        mUsbDevice = device;
                    }
                    if (mUsbDevice != null) {
                        try {
                            WCHUARTManager.getInstance().requestPermission(mContext, mUsbDevice);
                            SystemClock.sleep(200);
                            isResult = WCHUARTManager.getInstance().openDevice(mUsbDevice);
                            showLog("openDevice,结果：" + isResult);
                            if (isResult) {
                                ChipType2 type2 = WCHUARTManager.getInstance().getChipType(mUsbDevice);
                                showLog("芯片类型：" + type2.toString());
                                int serialCount = WCHUARTManager.getInstance().getSerialCount(mUsbDevice);
                                showLog("串口数目：" + serialCount);

                                setSerialParameter();
                                registerDataCallback();
                                isOpen = true;
                            }
                        } catch (ChipException e) {
                            showLog("openDevice,ChipException异常：" + e.toString());
                        } catch (NoPermissionException e) {
                            // showLog("openDevice,NoPermissionException异常：" + e.toString());
                            //没有权限打开该设备
                            //申请权限
                            WCHUARTManager.getInstance().requestPermission(mContext, mUsbDevice);
                            //openCOM(baudRate);
                        } catch (UartLibException e) {
                            showLog("openDevice,UartLibException异常：" + e.toString());
                        }
                    } else {
                        showLog("串口详情：mUsbDevice is null");
                    }
                }
            } else {
                showLog("usbDeviceArrayList为空");
            }
        } catch (Exception e) {
            showLog("enumDevice,异常：" + e.toString());
        }
        return isResult;
    }

    // 设置串口参数
    private void setSerialParameter() {
        try {
            //int botelv = 38400;
            boolean result = WCHUARTManager.getInstance().setSerialParameter(mUsbDevice, 0, ComTrUsb.baudRate, 8, 1, 0, false);
            // WCHUARTManager.getInstance().setRTS(mUsbDevice,0,true);
            // WCHUARTManager.getInstance().setDTR(mUsbDevice,0,true);
            showLog("setSerialParameter,结果：" + result);

        } catch (Exception e) {
            showLog("setSerialParameter,异常：" + e.toString());
        }
    }

    /**
     * 监测USB的状态
     */
    private void monitorUSBState() {
        WCHUARTManager.getInstance().setUsbStateListener(new IUsbStateChange() {
            @Override
            public void usbDeviceDetach(UsbDevice device) {
                // 设备移除
                showLog("设备移除：" + device.getDeviceName());


                if (device.getProductId() == mUsbDevice.getProductId() ) {
                    isOpen = false;
                }
            }

            @Override
            public void usbDeviceAttach(UsbDevice device) {
                // 设备插入
                showLog("设备插入：" + device.getDeviceName());
            }

            @Override
            public void usbDevicePermission(UsbDevice device, boolean result) {
                // 请求打开设备权限结果
                showLog("请求打开设备权限结果：" + device.getDeviceName() + " " + result);

            }
        });
    }


    /*
     * 发送16进制命令
     * */
    public void sendCMD(byte[] cmd) {
        //cmd = cmd.toUpperCase();
        //String msg = "发送命令：" + cmd;
//        showLog(msg);
        //msg = UtilTrUsb.TAG + msg;
        //以下是打印日志
        //byte[] bOutArray = FileUtils.hexStringToBytes(cmd);
        writeData(cmd);
    }

    // 写数据
    private void writeData(byte[] data) {
        try {
            int write = WCHUARTManager.getInstance().writeData(mUsbDevice, 0, data, data.length, 2000);
//            showLog("writeData,长度：" + write);
        } catch (Exception e) {
            showLog("writeData,异常：" + e.toString());
        }
    }


    public void setDataCallback(ReceiveDataCallback callback) {
        this.dataCallback = callback;
    }

    // 读数据
    private void registerDataCallback() {
        try {
            WCHUARTManager.getInstance().registerDataCallback(mUsbDevice, new IDataCallback() {
                @Override
                public void onData(int serialNumber, byte[] buffer, int length) {
                    byte[] data = new byte[length];
                    System.arraycopy(buffer, 0, data, 0, data.length);

                    String cmd = HexUtil.bytesToHexString(data);

                    if (TextUtils.isEmpty(cmd)) {
                        showLog("接收数据：null");
                    } else {



                        if (dataCallback != null) {
                            dataCallback.onReceiveData(cmd);
                        }


                    }

                }
            });
        } catch (Exception e) {
            showLog("registerDataCallback,异常：" + e.toString());
        }
    }

    private void showLog(String msg) {
        Log.d("ComTrUsb", msg);
        SerialPortApi.getInstance().showMsg(msg);
    }

    boolean flag = false;

    @Deprecated
    public class ReadThread extends Thread {

        public ReadThread() {
            flag = true;
            setPriority(Thread.MAX_PRIORITY);
        }

        @Override
        public void run() {

            while (flag) {



                if(mUsbDevice != null ) {
                    //读取该设备每个串口的数据

                        try {
                            byte[] bytes = WCHUARTManager.getInstance().readData(mUsbDevice, 0);
                            if (bytes != null) {
                                //使用获取到的数据
                                // updateReadData(device, i, bytes, bytes.length);
                                showLog(HexUtil.bytes2HexString(bytes));
                                //updateReadDataToFile(device,i,bytes,bytes.length);
                            }
                        } catch (ChipException e) {
                            //LogUtil.d(e.getMessage());
                            break;
                        } catch (Exception e) {

                            break;
                        }
                    }



            }

        }
    }



//    /**
//     * 从设备列表中打开某个设备
//     *
//     * @param usbDevice
//     */
//    void open(@NonNull UsbDevice usbDevice){
//        mUsbDevice = usbDevice;
//        if(WCHUARTManager.getInstance().isConnected(usbDevice)){
//            showLog("当前设备已经打开");
//            return;
//        }
//        try {
//            boolean b = WCHUARTManager.getInstance().openDevice(usbDevice);
//            if(b){
//                //打开成功
//                //更新显示的ui
//               // update(usbDevice);
//                //初始化接收计数
//                int serialCount = 0;
//                try {
//                    serialCount = WCHUARTManager.getInstance().getSerialCount(usbDevice);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//                for (int i = 0; i < serialCount; i++) {
//                    readCountMap.put(FormatUtil.getSerialKey(usbDevice,i),0);
//                }
//                //将该设备添加至已打开设备列表,在读线程ReadThread中,将会读取该设备的每个串口数据
//                addToReadDeviceSet(usbDevice);
//
//                registerModemStatusCallback(usbDevice);
//                if(!useReadThread){
//                    registerDataCallback(usbDevice);
//                }
//            }else {
//                showLog("打开失败");
//            }
//        } catch (ChipException e) {
//            showLog(e.getMessage());
//        } catch (NoPermissionException e) {
//            //没有权限打开该设备
//            //申请权限
//            showLog("没有权限打开该设备");
//            try {
//                WCHUARTManager.getInstance().requestPermission(mContext, mUsbDevice);
//            }
//            catch(Exception ee)
//            {
//                ee.printStackTrace();
//            }
//        } catch (UartLibException e) {
//            e.printStackTrace();
//        }
//    }
}
